<template>
  <GapedColumn width="100%">
    <search-fields
      ref="searchFieldsRef"
      :table-name="tableName"
      :option-fields="optionFields"
      :applyStorage="true"
    />
    <div class="form-actions">
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>
        检索
      </el-button>
    </div>
  </GapedColumn>
</template>

<script setup lang="ts">
import SearchFields from '@/components/SearchFields.vue'
import { GapedColumn } from '@/core/components'
import { ref, computed, defineProps } from 'vue'
import type { OptionField, Field } from './types'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'

interface Props {
  fields: Array<Field>
  tableName: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'search', params: any): void
  (e: 'reset'): void
}>()

const searchFieldsRef = ref()

const optionFields = computed<Array<OptionField>>(() => {
  return props.fields.map(field => {
    return {
      ...field,
      selected: false,
      alwaysSelected: field.type === 'daterange',
    }
  })
})

const handleSearch = async () => {
  if (!searchFieldsRef.value) return

  const params = await searchFieldsRef.value.generateSearchParams()
  emit('search', params)
}

const handleReset = () => {
  searchFieldsRef.value?.resetForm()
  emit('reset')
}
</script>

<style scoped>
.form-actions {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 16px;
}
</style>
